package com.pacs.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.pacs.model.UserWechats;
import com.pacs.model.Users;
import com.pacs.service.AccountService;
import com.pacs.service.ServiceFactory;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutCustomMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.msg.out.OutVoiceMsg;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由， 并设置好weixin开发者中心的 URL 与 token ，使
 * URL 指向该 DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgController extends MsgControllerAdapter {
	static {
		PropKit.use("config.txt");
		ServiceFactory.init();
	}
	static Log logger = Log.getLog(WeixinMsgController.class);
	private static final String helpStr = "\t你的品位不错哦  么么哒。";
	private static final String baseUrlStr = PropKit.get("wx_base_url");

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
	 * ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}

	public static ApiConfig getApiConfig2() {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
	
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msgContent = inTextMsg.getContent().trim();
		// 帮助提示
		if ("help".equalsIgnoreCase(msgContent) || "帮助".equals(msgContent)) {
			OutTextMsg outMsg = new OutTextMsg(inTextMsg);
			outMsg.setContent(helpStr);
			render(outMsg);
		} else if (msgContent.equals("8")) {
			String calbackUrl = PropKit.get("domain") + "/oauth";
			String url = SnsAccessTokenApi.getAuthorizeURL(PropKit.get("appId"), calbackUrl, "111", false);
			String urlStr = "<a href=\"" + url + "\">点击我授权</a>";
			System.out.println("urlStr " + urlStr);
			renderOutTextMsg("授权地址" + urlStr);
		} else if ("jssdk".equalsIgnoreCase(msgContent)) {
			String url = PropKit.get("domain") + "/jssdk";
			String urlStr = "<a href=\"" + url + "\">JSSDK</a>";
			renderOutTextMsg("地址" + urlStr);
		} else if ("我是医生".equalsIgnoreCase(msgContent)) {
			List<Articles> list = new ArrayList<Articles>();
			Articles articles1 = new Articles();
			articles1.setTitle("RIS Online");
			articles1.setDescription("医生朋友你好，点击此处进入“中世康恺RIS”，使用用户名和密码登录，轻松查看电子胶片，撰写报告");
			articles1.setUrl("http://ris.pacsonline.cn");
			Articles articles2 = new Articles();
			articles2.setTitle("点击查看《RIS操作指南》");
			articles2.setDescription("医生朋友你好，点击查看我们为你准备的这份指南，写报告，看电子胶片、对比、测量，全靠它");
			articles2.setUrl("http://wechat.pacsonline.cn/doc/fuyu");
			list.add(articles1);
			list.add(articles2);
			CustomServiceApi.sendNews(inTextMsg.getFromUserName(), list);
			renderNull();
		} else if ("一建医院".equalsIgnoreCase(msgContent)) {
			List<Articles> list = new ArrayList<Articles>();
			Articles articles1 = new Articles();
			articles1.setTitle("RIS Online");
			articles1.setDescription("医生朋友你好，点击此处进入“中世康恺RIS”，使用用户名和密码登录，轻松查看电子胶片，撰写报告");
			articles1.setUrl("http://ris.pacsonline.cn");
			Articles articles2 = new Articles();
			articles2.setTitle("《RIS操作指南》");
			articles2.setDescription("医生朋友你好，点击查看我们为你准备的这份指南，写报告，看电子胶片、对比、测量，全靠它");
			articles2.setUrl("http://wechat.pacsonline.cn/doc/zhaodong");
			list.add(articles1);
			list.add(articles2);
			CustomServiceApi.sendNews(inTextMsg.getFromUserName(), list);
			renderNull();
		} else if ("模板消息".equalsIgnoreCase(msgContent)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
			String time = sdf.format(new Date());
			String json = TemplateData.New().setTouser(inTextMsg.getFromUserName())
					.setTemplate_id("BzC8RvHu1ICOQfO4N7kp6EWz9VAbISJjV2fO5t7MiXE").setTopcolor("#743A3A")
					.setUrl("http://www.cnblogs.com/zyw-205520/tag/%E5%BE%AE%E4%BF%A1/")
					.add("first", "您好,你已购买课程成功", "#743A3A").add("keyword1", "微信公众号开发公开课", "#0000FF")
					.add("keyword2", "免费", "#0000FF").add("keyword3", "Javen205", "#0000FF")
					.add("keyword4", time, "#0000FF").add("remark", "请点击详情直接看课程直播，祝生活愉快", "#008000").build();
			System.out.println(json);
			ApiResult result = TemplateMsgApi.send(json);
			System.out.println(result.getJson());
			renderNull();
		} else if ("异步回复多个消息".equals(msgContent)) {
			final String toUser = inTextMsg.getFromUserName();
			new Thread(new Runnable() {
				@Override
				public void run() {
					ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
					ApiResult sendText = CustomServiceApi.sendText(toUser, "客服消息");
					System.out.println(sendText.getJson());
					List<Articles> list = new ArrayList<Articles>();
					Articles articles1 = new Articles();
					articles1.setTitle("测试异步回复多个消息");
					articles1.setDescription("客服多图文消息");
					articles1.setPicurl(
							"http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1609/27/c0/27587202_1474952311163_800x600.jpg");
					articles1.setUrl("http://www.cnblogs.com/zyw-205520/tag/%E5%BE%AE%E4%BF%A1/");
					Articles articles2 = new Articles();
					articles2.setTitle("微信买单、刷卡、扫码、公众号支付");
					articles2.setDescription("微信支付教程");
					articles2.setPicurl(
							"http://desk.fd.zol-img.com.cn/t_s960x600c5/g4/M01/0D/04/Cg-4WVP_npmIY6GRAKcKYPPMR3wAAQ8LgNIuTMApwp4015.jpg");
					articles2.setUrl("http://www.jianshu.com/notebooks/2736169/latest");
					list.add(articles2);
					list.add(articles1);
					CustomServiceApi.sendNews(toUser, list);
				}
			}).start();
			// 回复被动响应消息
			renderOutTextMsg("你发的内容为：" + msgContent);
		}
		else {
			renderNull();
			// 转发给多客服PC客户端
			// OutCustomMsg outCustomMsg = new OutCustomMsg(inTextMsg);
			// render(outCustomMsg);
		}
	}

	@Override
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
		// 转发给多客服PC客户端
		// OutCustomMsg outCustomMsg = new OutCustomMsg(inVoiceMsg);
		// render(outCustomMsg);
		OutVoiceMsg outMsg = new OutVoiceMsg(inVoiceMsg);
		// 将刚发过来的语音再发回去
		outMsg.setMediaId(inVoiceMsg.getMediaId());
		render(outMsg);
	}

	@Override
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {
		/*
		 * 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试 OutVideoMsg outMsg = new
		 * OutVideoMsg(inVideoMsg); outMsg.setTitle("OutVideoMsg 发送");
		 * outMsg.setDescription("刚刚发来的视频再发回去"); // 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api
		 * 有 bug，待 api bug 却除后再试 outMsg.setMediaId(inVideoMsg.getMediaId());
		 * render(outMsg);
		 */
		OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
		outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inVideoMsg.getMediaId());
		render(outMsg);
	}

	@Override
	protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
		OutTextMsg outMsg = new OutTextMsg(inShortVideoMsg);
		outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inShortVideoMsg.getMediaId());
		render(outMsg);
	}

	@Override
	protected void processInLocationMsg(InLocationMsg inLocationMsg) {
		OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
		outMsg.setContent("已收到地理位置消息:" + "\nlocation_X = " + inLocationMsg.getLocation_X() + "\nlocation_Y = "
				+ inLocationMsg.getLocation_Y() + "\nscale = " + inLocationMsg.getScale() + "\nlabel = "
				+ inLocationMsg.getLabel());
		render(outMsg);
	}

	@Override
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
		// 转发给多客服PC客户端
		OutCustomMsg outCustomMsg = new OutCustomMsg(inLinkMsg);
		render(outCustomMsg);
	}

	@Override
	protected void processInCustomEvent(InCustomEvent inCustomEvent) {
		logger.debug("测试方法：processInCustomEvent()");
		renderNull();
	}

	protected void processInImageMsg(InImageMsg inImageMsg) {
		// 转发给多客服PC客户端
		// OutCustomMsg outCustomMsg = new OutCustomMsg(inImageMsg);
		// render(outCustomMsg);
		String picUrl = inImageMsg.getPicUrl();
		String respContent = "";
		renderOutTextMsg(respContent);
	}

	/**
	 * 实现父类抽方法，处理关注/取消关注消息
	 */
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {
			logger.debug("关注：" + inFollowEvent.getFromUserName());
			OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
			UserWechats findUserWechats = UserWechats.dao.findById(inFollowEvent.getFromUserName());
			if (findUserWechats == null) {
				AccountService aService = ServiceFactory.getService(AccountService.class);
				Users users = aService.createWxUser(inFollowEvent.getFromUserName());
				
				List<Articles> list = new ArrayList<Articles>();
				Articles articles1 = new Articles();
				articles1.setTitle("欢迎关注黑龙江省电子胶片平台，点此进入");
				articles1.setDescription("点击页面绑定手机号或身份证号，立即查看电子胶片");
				articles1.setUrl("http://wechat.pacsonline.cn/pacs_online/html/bind.html?uid=" + users.getId());
				list.add(articles1);
				CustomServiceApi.sendNews(inFollowEvent.getFromUserName(), list);
			}else {
				findUserWechats.setSubscribeStstus(1);
				findUserWechats.update();
				OutTextMsg outMsgs = new OutTextMsg(inFollowEvent);
				outMsgs.setContent("欢迎关注黑龙江省电子胶片平台！\n使用微信-“扫一扫”，扫描报告上的二维码，即可查看电子影像和报告");
				render(outMsgs);
			}
		}
		// 如果为取消关注事件，将无法接收到传回的信息
		if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent())) {
			logger.debug("取消关注：" + inFollowEvent.getFromUserName());
			UserWechats findUserWechats = UserWechats.dao.findById(inFollowEvent.getFromUserName());
			findUserWechats.setSubscribeStstus(0);
			findUserWechats.update();
		}
	}

	private String creatToken() {
		return UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
	}

	private Integer getCurrentTime() {
		return (int)(System.currentTimeMillis()/1000);
	}
	
	@Override
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		System.out.println("扫码.......");
		if (InQrCodeEvent.EVENT_INQRCODE_SUBSCRIBE.equals(inQrCodeEvent.getEvent())) {
			UserWechats findUserWechats = UserWechats.dao.findById(inQrCodeEvent.getFromUserName());
			String rid = inQrCodeEvent.getEventKey();
			String[] arr = rid.split("_");

			if (findUserWechats == null) {
				AccountService aService = ServiceFactory.getService(AccountService.class);
                Users users = aService.createWxUser(inQrCodeEvent.getFromUserName());
				
				List<Articles> list = new ArrayList<Articles>();
				Articles articles1 = new Articles();
				articles1.setTitle("欢迎关注黑龙江省电子胶片平台");
				articles1.setDescription("点击绑定手机号或身份证号,永久保存胶片和报告");
				articles1.setUrl("http://wechat.pacsonline.cn/pacs_online/html/bind.html?uid=" + users.getId());
				list.add(articles1);
				Articles articles2 = new Articles();
				articles2.setTitle("点击查看本次影像和报告");
				articles2.setDescription("欢迎使用中世康恺PacsOnline！\n点击进入查看详情，您可以分享给家属或医生，日后还可以在“我的报告”中查看本次影像和报告");
				articles2.setUrl("http://wechat.pacsonline.cn/pacs_online/html/report_prepare.html?reportId=" + arr[2]+"&uid="+users.getId());
				list.add(articles2);
				CustomServiceApi.sendNews(inQrCodeEvent.getFromUserName(), list);
				renderNull();
				
			}else {
				findUserWechats.setSubscribeStstus(1);
				findUserWechats.update();

				ApiResult sendText = CustomServiceApi.sendText(inQrCodeEvent.getFromUserName(), "欢迎关注黑龙江省电子胶片平台！\n使用微信-“扫一扫”，扫描报告上的二维码，即可查看电子影像和报告");

				List<Articles> list = new ArrayList<Articles>();
				Articles articles1 = new Articles();
				articles1.setTitle("点击查看本次影像和报告");
				articles1.setDescription("欢迎使用中世康恺PacsOnline！\n点击进入查看详情，您可以分享给家属或医生，日后还可以在“我的报告”中查看本次影像和报告");
				articles1.setUrl("http://wechat.pacsonline.cn/pacs_online/html/report_prepare.html?reportId=" + arr[2]+"&uid="+findUserWechats.getUid());
				list.add(articles1);
				CustomServiceApi.sendNews(inQrCodeEvent.getFromUserName(), list);
				renderNull();
				
			}		
		}
		if (InQrCodeEvent.EVENT_INQRCODE_SCAN.equals(inQrCodeEvent.getEvent())) {
			logger.debug("扫码已关注：" + inQrCodeEvent.getFromUserName());
			String rid = inQrCodeEvent.getEventKey();
			String[] arr = rid.split("_");
			UserWechats userWechats = UserWechats.dao.findById(inQrCodeEvent.getFromUserName());
		
			List<Articles> list = new ArrayList<Articles>();
			Articles articles1 = new Articles();
			articles1.setTitle("点击查看本次影像和报告");
			articles1.setDescription("欢迎使用中世康恺PacsOnline！\n点击进入查看详情，您可以分享给家属或医生，日后还可以在“我的报告”中查看本次影像和报告");
			articles1.setUrl("http://wechat.pacsonline.cn/pacs_online/html/report_prepare.html?reportId=" + arr[1]+"&uid="+userWechats.getUid());
			list.add(articles1);
			CustomServiceApi.sendNews(inQrCodeEvent.getFromUserName(), list);
			renderNull();
		}

	}

	@Override
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		logger.debug("发送地理位置事件：" + inLocationEvent.getFromUserName());
		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
		outMsg.setContent("地理位置是：" + inLocationEvent.getLatitude());
		render(outMsg);
	}

	@Override
	protected void processInMassEvent(InMassEvent inMassEvent) {
		logger.debug("测试方法：processInMassEvent()");
		renderNull();
	}

	/**
	 * 实现父类抽方法，处理自定义菜单事件
	 */
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		logger.debug("菜单事件：" + inMenuEvent.getFromUserName());
		OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
		outMsg.setContent("菜单事件内容是：" + inMenuEvent.getEventKey());
		// render(outMsg);
		if (inMenuEvent.getEventKey().equals("模板消息")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
			String time = sdf.format(new Date());
			String json = TemplateData.New().setTouser("oBoXi0rjBND63lZJc9ictaZoz5B4")
					.setTemplate_id("459YlhAGJyOD0Bmt9c1zcLypXb7QawjqEfxpeUvdy6w").setTopcolor("#743A3A")
					.setUrl(baseUrlStr + "/wx/my").add("first", "您好,准备好进行研究了吗，GO！", "#743A3A").build();
			System.out.println(json);
			ApiResult result = TemplateMsgApi.send(json);
			System.out.println(result.getJson());
		}
		renderNull();
	}

	@Override
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
		logger.debug("语音识别事件：" + inSpeechRecognitionResults.getFromUserName());
		OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
		outMsg.setContent("语音识别内容是：" + inSpeechRecognitionResults.getRecognition());
		render(outMsg);
	}

	@Override
	protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
		logger.debug("测试方法：processInTemplateMsgEvent()");
		renderNull();
	}

	public static void ssss() {

		ApiConfigKit.setThreadLocalApiConfig(getApiConfig2());

		List<Articles> list = new ArrayList<Articles>();

		Articles articles1 = new Articles();
		articles1.setTitle("欢迎您加入真实世界研究");
		articles1.setDescription("填问卷赢积分，更多服务等您尊享");
//		articles1.setPicurl("http://static.cyyzjk.com/FvtEdfxn-ECgM6dY1Z-Gay5-CbDk.jpg");
		articles1.setUrl(baseUrlStr + "/wx/setInfo");

		list.add(articles1);

//		CustomServiceApi.sendNews("oBoXi0rjBND63lZJc9ictaZoz5B4", list);
		CustomServiceApi.sendText("o-jR00R80hWFcIV8_8DqmgEhYUjw", "您开始用药了吗\n<a href=\"www.baidu.com\">点击设置用药时间</a>");
	}

	public static void main(String[] args) {
		PropKit.use("config.txt");
		ServiceFactory.init();
		ssss();
	}
}
